<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-framework-SpringCloud-4 - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="Feign负载均衡 Feign官方文档：http://projects.spring.io/spring-cloud/spring-cloud" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-framework-SpringCloud-4 - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-framework-SpringCloud-4" />
<meta property="og:description" content="Feign负载均衡 Feign官方文档：http://projects.spring.io/spring-cloud/spring-cloud" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-4/" />
<meta property="article:published_time" content="2019-08-25T12:10:30+08:00" />
<meta property="article:modified_time" content="2019-08-25T12:10:30+08:00" />
<meta itemprop="name" content="Java-framework-SpringCloud-4">
<meta itemprop="description" content="Feign负载均衡 Feign官方文档：http://projects.spring.io/spring-cloud/spring-cloud">
<meta itemprop="datePublished" content="2019-08-25T12:10:30&#43;08:00" />
<meta itemprop="dateModified" content="2019-08-25T12:10:30&#43;08:00" />
<meta itemprop="wordCount" content="3997">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-framework-SpringCloud-4"/>
<meta name="twitter:description" content="Feign负载均衡 Feign官方文档：http://projects.spring.io/spring-cloud/spring-cloud"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/mongodb-1/" class="title">MonggoDB-1</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-03 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-03</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2019/08/java-framework-springcloud-4/"
    >Java-framework-SpringCloud-4</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-4/" class="article-date">
  <time datetime="2019-08-25 12:10:30 &#43;0800 CST" itemprop="datePublished">2019-08-25</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-framework/"> Java-framework </a>
</span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2019/08/java-framework-springcloud-4/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 3997words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 8minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="feign负载均衡">Feign负载均衡</h1>
<p>Feign官方文档：http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign</p>
<h2 id="为什么会有feign">为什么会有Feign</h2>
<p>一句话：只需要创建一个接口，然后在上面添加注解即可</p>
<p>为什么要有Feign？</p>
<p>答：Feign旨在使编写Java Http客户端变得更容易。前面在使用Ribbon+RestTemplate，在Feign的实现下，我们只需创建一个接口并使用注解的方式来配置它(以前是Dao接口上面标注Mapper注解,现在是一个微服务接口上面标注一个Feign注解即可)</p>
<h2 id="如何使用feign">如何使用Feign</h2>
<p>1）参考microservicecloud-consumer-dept-80，新建模块：microservicecloud-consumer-dept-feign</p>
<p>2）pom.xml</p>
<p>除了microservicecloud-consumer-dept-80中的依赖外，还需添加Feign依赖包</p>
<pre><code>   &lt;dependency&gt;
       &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
       &lt;artifactId&gt;spring-cloud-starter-feign&lt;/artifactId&gt;
   &lt;/dependency&gt;
</code></pre>
<p>3）修改microservicecloud-api模块</p>
<p>在microservicecloud-api的pom.xml添加feign依赖</p>
<pre><code>   &lt;dependency&gt;
     &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
     &lt;artifactId&gt;spring-cloud-starter-feign&lt;/artifactId&gt;
   &lt;/dependency&gt;
</code></pre>
<p>新增DeptClientService接口，并用@FeignClient修饰</p>
<pre><code class="language-java">@FeignClient(value = &quot;MICROSERVICECLOUD-DEPT&quot;)
public interface DeptClientService
{
  @RequestMapping(value = &quot;/dept/get/{id}&quot;,method = RequestMethod.GET)
  public Dept get(@PathVariable(&quot;id&quot;) long id);
 
  @RequestMapping(value = &quot;/dept/list&quot;,method = RequestMethod.GET)
  public List&lt;Dept&gt; list();
 
  @RequestMapping(value = &quot;/dept/add&quot;,method = RequestMethod.POST)
  public boolean add(Dept dept);
}
</code></pre>
<p>4）修改microservicecloud-consumer-dept-feign模块的controller</p>
<pre><code class="language-java">@RestController
public class DeptController_Feign
{
  @Autowired
  private DeptClientService service = null;
 
  @RequestMapping(value = &quot;/consumer/dept/get/{id}&quot;)
  public Dept get(@PathVariable(&quot;id&quot;) Long id)
  {
   return this.service.get(id);
  }
 
  @RequestMapping(value = &quot;/consumer/dept/list&quot;)
  public List&lt;Dept&gt; list()
  {
   return this.service.list();
  }
 
  @RequestMapping(value = &quot;/consumer/dept/add&quot;)
  public Object add(Dept dept)
  {
   return this.service.add(dept);
  }
}
</code></pre>
<p>5）microservicecloud-consumer-dept-feign模块，主启动类</p>
<p>添加两个注解@EnableFeignClients、@ComponentScan</p>
<pre><code class="language-java">@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages= {&quot;com.atguigu.springcloud&quot;})
public class DeptConsumer80_Feign_App
{
	public static void main(String[] args)
	{
		SpringApplication.run(DeptConsumer80_Feign_App.class, args);
	}
}
</code></pre>
<p>注意：包名要写对，com.atguigu.springcloud，跟<code>@FeignClient</code>所有的包一致</p>
<p>6）总结</p>
<p>重点在第三步，接口+@FeignClient，通过实例名称找到微服务，并隐藏了RestTemplate</p>
<h1 id="hystrix断路器">Hystrix断路器</h1>
<p>复杂分布式体系结构中的应用程序有数十个依赖关系，每个依赖关系在某些时候将不可避免地失败。</p>
<p>Hystrix能够保证在一个依赖出问题的情况下，不会导致整体服务失败，避免级联故障，以提高分布式系统的弹性。</p>
<p>“断路器”本身是一种开关装置，当某个服务单元发生故障之后，通过断路器的故障监控（类似熔断保险丝），<strong>向调用方返回一个符合预期的、可处理的备选响应（FallBack）</strong>，而不是长时间的等待或者抛出调用方无法处理的异常</p>
<p>官方文档：https://github.com/Netflix/Hystrix/wiki</p>
<h2 id="服务容断">服务容断</h2>
<p>熔断机制的注解是@HystrixCommand</p>
<p>代码步骤：</p>
<p>1）参考microservicecloud-provider-dept-8001，新建microservicecloud-provider-dept-hystrix-8001</p>
<pre><code class="language-xml">  &lt;!-- hystrix --&gt;
   &lt;dependency&gt;
     &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
     &lt;artifactId&gt;spring-cloud-starter-hystrix&lt;/artifactId&gt;
   &lt;/dependency&gt;
</code></pre>
<p>2）controller的相应方法使用@HystrixCommand，并写回调函数</p>
<pre><code class="language-java">@RestController
public class DeptController {

    @Autowired
    private DeptService service = null;

    @RequestMapping(value = &quot;/dept/get/{id}&quot;, method = RequestMethod.GET)
    //一旦调用服务方法失败并抛出了错误信息后，会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
    @HystrixCommand(fallbackMethod = &quot;processHystrix_Get&quot;)
    public Dept get(@PathVariable(&quot;id&quot;) Long id)
    {

        Dept dept = this.service.get(id);

        if (null == dept) {
            throw new RuntimeException(&quot;该ID：&quot; + id + &quot;没有没有对应的信息&quot;);
        }

        return dept;
    }

    public Dept processHystrix_Get(@PathVariable(&quot;id&quot;) Long id)
    {
        return new Dept().setDeptno(id).setDname(&quot;该ID：&quot; + id + &quot;没有没有对应的信息,null--@HystrixCommand&quot;)
                .setDb_source(&quot;no this database in MySQL&quot;);
    }
}
</code></pre>
<p>3）主启动类上开启Hystrix：@EnableCircuitBreaker</p>
<pre><code class="language-java">@SpringBootApplication
@EnableEurekaClient // 或使用@EnableDiscoveryClient  不同点：@EnableEurekaClient只适用于Eureka作为注册中心，@EnableDiscoveryClient 可以是其他注册中心
@EnableCircuitBreaker //对hystrixR熔断机制的支持
public class DeptProvider8001_App {
    public static void main(String[] args) {
        SpringApplication.run(DeptProvider8001_App.class, args);
    }
}
</code></pre>
<p>4）测试</p>
<ul>
<li>启动三个eureka集群</li>
<li>启动服务提供者：microservicecloud-provider-dept-hystrix-8001</li>
<li>启动服务消费者：microservicecloud-consumer-dept-80</li>
</ul>
<p>4.1：查看是否正常注册：http://eureka7001.com:7001/
<img src="https://oscimg.oschina.net/oscnet/up-bba677eca826efec15e11e5ec500ed31715.png" alt=""></p>
<p>4.2：查看hystrix：http://localhost/consumer/dept/get/13</p>
<p>没有ID为13的信息，null，返回以下信息</p>
<pre><code>{&quot;deptno&quot;:13,&quot;dname&quot;:&quot;该ID：13没有没有对应的信息,null--@HystrixCommand&quot;,&quot;db_source&quot;:&quot;no this database in MySQL&quot;}
</code></pre>
<h2 id="服务降级">服务降级</h2>
<p>整体资源快不够了，忍痛将某些服务先关掉，待渡过难关，再开启回来。</p>
<p>服务降级处理是<strong>在客户端实现的</strong>，与服务端没有关系</p>
<p>步骤：</p>
<p>1）修改microservicecloud-api工程</p>
<p>根据已经有的DeptClientService接口新建一个实现了FallbackFactory接口的DeptClientServiceFallbackFactory</p>
<pre><code class="language-java">@Component//不要忘记添加，不要忘记添加
public class DeptClientServiceFallbackFactory implements FallbackFactory&lt;DeptClientService&gt;
{
  @Override
  public DeptClientService create(Throwable throwable)
  {
   return new DeptClientService() {
     @Override
     public Dept get(long id)
     {
       return new Dept().setDeptno(id)
               .setDname(&quot;该ID：&quot;+id+&quot;没有没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭&quot;)
               .setDb_source(&quot;no this database in MySQL&quot;);
     }
 
     @Override
     public List&lt;Dept&gt; list()
     {
       return null;
     }
 
     @Override
     public boolean add(Dept dept)
     {
       return false;
     }
   };
  }
}
</code></pre>
<p>注意此类一定要用@Component修饰</p>
<p>2）修改microservicecloud-api工程</p>
<p>在DeptClientService接口的@FeignClient注解中添加fallbackFactory属性</p>
<pre><code class="language-java">@FeignClient(value = &quot;MICROSERVICECLOUD-DEPT&quot;,fallbackFactory = DeptClientServiceFallbackFactory.class)
public interface DeptClientService
{
  @RequestMapping(value = &quot;/dept/get/{id}&quot;,method = RequestMethod.GET)
  public Dept get(@PathVariable(&quot;id&quot;) long id);
 
  @RequestMapping(value = &quot;/dept/list&quot;,method = RequestMethod.GET)
  public List&lt;Dept&gt; list();
 
  @RequestMapping(value = &quot;/dept/add&quot;,method = RequestMethod.POST)
  public boolean add(Dept dept);
}
</code></pre>
<p>3）将microservicecloud-api工程重新安装到本地maven目录</p>
<pre><code>mvn clean install
</code></pre>
<p>4）修改microservicecloud-consumer-dept-feign工程的yml</p>
<p>添加以下配置：</p>
<pre><code>feign: 
  hystrix: 
    enabled: true
</code></pre>
<p>5）测试</p>
<ul>
<li>启动3个eureka</li>
<li>启动服务提供者：microservicecloud-provider-dept-8001</li>
<li>启动服务消息者：microservicecloud-consumer-dept-feign</li>
</ul>
<p>正常访问：http://localhost/consumer/dept/get/1</p>
<p>故意停止microservicecloud-provider-dept-8001，再访问，则：</p>
<pre><code>{&quot;deptno&quot;:1,&quot;dname&quot;:&quot;该ID：1没有没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭&quot;,&quot;db_source&quot;:&quot;no this database in MySQL&quot;}
</code></pre>
<p><strong>服务熔断、降级小结</strong>：</p>
<ul>
<li>服务熔断：需要在每个controller方法上使用@HystrixCommand注解并指定回调函数</li>
<li>服务降级：使用切面方式将回调函数写在一个接口中</li>
</ul>
<h2 id="服务监控hystrixdashboard">服务监控——hystrixDashboard</h2>
<p>除了隔离依赖服务的调用以外，Hystrix还提供了准实时的调用监控（Hystrix Dashboard），Hystrix会持续地记录所有通过Hystrix发起的请求的执行信息，并以统计报表和图形的形式展示给用户，包括每秒执行多少请求多少成功，多少失败等。</p>
<p>Netflix通过hystrix-metrics-event-stream项目实现了对以上指标的监控。Spring Cloud也提供了Hystrix Dashboard的整合，对监控内容转化成可视化界面。</p>
<p>示例-步骤：</p>
<p>1）新建microservicecloud-consumer-hystrix-dashboard项目</p>
<p>2）pom.xml导入依赖</p>
<pre><code class="language-xml">   &lt;!-- hystrix和 hystrix-dashboard相关--&gt;
   &lt;dependency&gt;
       &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
       &lt;artifactId&gt;spring-cloud-starter-hystrix&lt;/artifactId&gt;
   &lt;/dependency&gt;
   &lt;dependency&gt;
       &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;
       &lt;artifactId&gt;spring-cloud-starter-hystrix-dashboard&lt;/artifactId&gt;
   &lt;/dependency&gt; 
</code></pre>
<p>3）application.yml</p>
<pre><code>server:
  port: 9001
</code></pre>
<p>4）主启动类使用新注解@EnableHystrixDashboard</p>
<pre><code>@SpringBootApplication
@EnableHystrixDashboard
public class DeptConsumer_DashBoard_App
{
  public static void main(String[] args)
  {
   SpringApplication.run(DeptConsumer_DashBoard_App.class,args);
  }
}
</code></pre>
<p>5）所有的服务提供者都添加监控依赖actuator</p>
<p>所有的服务提供者（8001、8002、8003）都添加监控依赖actuator</p>
<pre><code>   &lt;!-- actuator监控信息完善 --&gt;
   &lt;dependency&gt;
     &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
     &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;
   &lt;/dependency&gt;
</code></pre>
<p>6）测试</p>
<ul>
<li>先启动 microservicecloud-consumer-hystrix-dashboard 监控消费端：http://localhost:9001/hystrix</li>
<li>启动三个eureka集群</li>
<li>启动 microservicecloud-provider-dept-hystrix-8001，访问：http://localhost:8001/hystrix.stream ，将看到很多JSON数据，这不是图形化</li>
<li>图形化：
<img src="https://oscimg.oschina.net/oscnet/up-1c8df240c05753f629efbd2fd737579f3ec.png" alt=""></li>
</ul>
<p>如何看懂上面的图形？7色、1圈、1线</p>
<ul>
<li>7色：</li>
<li>实心圆：共有两种含义。它通过颜色的变化代表了实例的健康程度，它的健康度从绿色&lt;黄色&lt;橙色&lt;红色递减。</li>
<li>曲线：用来记录2分钟内流量的相对变化，可以通过它来观察到流量的上升和下降趋势。
<img src="https://oscimg.oschina.net/oscnet/up-2cc1e1f5b151dafa116f812f5fb7ed8b63f.png" alt=""></li>
</ul>
<p>7）总结</p>
<ol>
<li>监控应用（http://localhost:9001/hystrix ）独立部署，内部代码不需要调用其它服务，只需在页面填写要监控的地址</li>
<li>只能监控开启了熔断机制的应用（主启动类有@EnableCircuitBreaker）</li>
</ol>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-4/" title="Java-framework-SpringCloud-4" target="_blank" rel="external">https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-4/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-3/" title="Java-framework-SpringCloud-3"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2019/08/java-framework-springcloud-5/"
                    title="Java-framework-SpringCloud-5"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2017  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
